﻿using Domain;
using Domain.Entity;
using Domain.Repository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace EFCore.Repositorys
{
    public class HFRepository : IHFRepository
    {
        private readonly MyDbContext myDbContext;

        public HFRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        public HFFenYE HFfenye(string firstKindName, string secondKindName, string thirdKindName, DateTime startDate, DateTime endDate, int page, int pageSize)
        {
			var query = myDbContext.HF.AsQueryable();
			query = query.Where(s => s.HumanFileStatus != 3);

			// 当三个数据都有值时，只查询符合条件的数据  
			if (!string.IsNullOrEmpty(firstKindName) && !string.IsNullOrEmpty(secondKindName) && !string.IsNullOrEmpty(thirdKindName))
            {
                query = query.Where(s => s.FirstKindName == firstKindName
                                         && s.SecondKindName == secondKindName
                                         && s.ThirdKindName == thirdKindName);
            }
            // 当 firstKindName 和 secondKindName 有值，而 thirdKindName 没有值时  
            else if (!string.IsNullOrEmpty(firstKindName) && !string.IsNullOrEmpty(secondKindName) && string.IsNullOrEmpty(thirdKindName))
            {
                query = query.Where(s => s.FirstKindName == firstKindName
                                         && s.SecondKindName == secondKindName
                                         && string.IsNullOrEmpty(s.ThirdKindName));
            }
            // 当只有 firstKindName 有值的时候  
            else if (!string.IsNullOrEmpty(firstKindName) && string.IsNullOrEmpty(secondKindName) && string.IsNullOrEmpty(thirdKindName))
            {
                query = query.Where(s => s.FirstKindName == firstKindName
                                         && string.IsNullOrEmpty(s.SecondKindName)
                                         && string.IsNullOrEmpty(s.ThirdKindName));
            }

			if (startDate != default && endDate != default)
			{
				query = query.Where(s => s.RegistTime >= startDate && s.RegistTime <= endDate);
			}

			int totalRecords = query.Count();
			var HF = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();

			return new HFFenYE
			{
				totalRecords = totalRecords,
				hf = HF
			};
		}
        public async Task<bool> AddHFAsync(HF hf)
        {
            myDbContext.HF.Add(hf);
            int result = await myDbContext.SaveChangesAsync();
            return result > 0;
        }

        public HFFenYE FenYeHFAsync(int zt, int page, int pageSize)
        {
            var query = myDbContext.HF.AsQueryable();

            if (!string.IsNullOrEmpty(zt.ToString()))
            {
                query = query.Where(s => s.CheckStatus == zt);
            }
            int totalRecords = query.Count();
            var HF = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
            return new HFFenYE
            {
                totalRecords = totalRecords,
                hf = HF
            };
        }

        public HFQuery SelectHFQAsync(string zhi)

        {
            List<HFGROUPBY> hFQueryGB = new List<HFGROUPBY>();
            if (zhi == "1")
            {
                var groupedResults = myDbContext.HF
               .Where(hf => hf.ThirdKindName == null && hf.SecondKindName == null && hf.HumanFileStatus == 1 &&hf.CheckStatus == 2)
               .GroupBy(hf => hf.FirstKindName)
               .ToList();
                int serialNumber = 1;
                foreach (var group in groupedResults)
                {
                    hFQueryGB.Add(new HFGROUPBY()
                    {
                        XuHao = serialNumber++,
                        hF = group.ToList(),
                        Nme = group.Key,
                        RecordCount = group.Count(),
                        TotalSalarySum = (double)group.Sum(hf => hf.SalarySum),
                        TotalPaidSalarySum = (double)group.Sum(hf => hf.PaidSalarySum)
                    });
                }
            }
            else if (zhi == "2")
            {
                var groupedResults = myDbContext.HF
                    .Where(hf => hf.SecondKindName != null && hf.ThirdKindName == null && hf.HumanFileStatus == 1 && hf.CheckStatus == 2)
                    .GroupBy(hf => hf.SecondKindName)
                    .ToList();

                int serialNumber = 1;
                foreach (var group in groupedResults)
                {
                    hFQueryGB.Add(new HFGROUPBY()
                    {
                        XuHao = serialNumber++,
                        hF = group.ToList(),
                        Nme = group.Key,
                        RecordCount = group.Count(),
                        TotalSalarySum = (double)group.Sum(hf => hf.SalarySum),
                        TotalPaidSalarySum = (double)group.Sum(hf => hf.PaidSalarySum)
                    });
                }
            }
            else
            {
                var groupedResults = myDbContext.HF
                    .Where(hf => hf.ThirdKindName != null && hf.HumanFileStatus == 1 && hf.CheckStatus == 2)
                    .GroupBy(hf => hf.ThirdKindName)
                    .ToList();

                int serialNumber = 1;
                foreach (var group in groupedResults)
                {
                    hFQueryGB.Add(new HFGROUPBY()
                    {
                        XuHao = serialNumber++,
                        hF = group.ToList(),
                        Nme = group.Key,
                        RecordCount = group.Count(),
                        TotalSalarySum = (double)group.Sum(hf => hf.SalarySum),
                        TotalPaidSalarySum = (double)group.Sum(hf => hf.PaidSalarySum)
                    });
                }
            }
            HFQuery hFQuery = new HFQuery
            {
                hf = hFQueryGB,
                totalRecords = hFQueryGB.Count,
                headcount = hFQueryGB.Sum(item => item.RecordCount),
                totalCost = hFQueryGB.Sum(item => item.TotalSalarySum),
                totalCostS = hFQueryGB.Sum(item => item.TotalPaidSalarySum)

            };
            return hFQuery;
        }

        public async Task<bool> UpdateHFAsync(HF hf)
        {
            HF hF = myDbContext.HF.Where(e => e.HufId == hf.HufId).FirstOrDefault();
            SS ss= myDbContext.SS.Where(e => e.StandardId == hf.SalaryStandardId).FirstOrDefault();
			hF.FirstKindId = hf.FirstKindId;
            hF.FirstKindName = hf.FirstKindName;
            hF.SecondKindId = hf.SecondKindId;
            hF.SecondKindName = hf.SecondKindName;
            hF.ThirdKindId = hf.ThirdKindId;
            hF.ThirdKindName = hf.ThirdKindName;
            hF.HumanMajorKindId = hf.HumanMajorKindId;
            hF.HumanMajorKindName = hf.HumanMajorKindName;
            hF.HumanMajorId = hf.HumanMajorId;
            hF.HumanProDesignation = hf.HumanProDesignation;
            hF.HumanName = hf.HumanName;
            hF.HumanSex = hf.HumanSex;
            hF.HumanEmail = hf.HumanEmail;
            hF.HumanTelephone = hf.HumanTelephone;
            hF.HumanQQ = hf.HumanQQ;
            hF.HumanMobilephone = hf.HumanMobilephone;
            hF.HumanAddress = hf.HumanAddress;
            hF.HumanPostcode = hf.HumanPostcode;
            hF.HumanNationality = hf.HumanNationality;
            hF.HumanBirthplace = hf.HumanBirthplace;
            hF.HumanBirthday = hf.HumanBirthday;
            hF.HumanRace = hf.HumanRace;
            hF.HumanReligion = hf.HumanReligion;
            hF.HumanParty = hf.HumanParty;
            hF.HumanIdCard = hf.HumanIdCard;
            hF.HumanSocietySecurityId = hf.HumanSocietySecurityId;
            hF.HumanAge = hf.HumanAge;
            hF.HumanEducatedDegree = hf.HumanEducatedDegree;
            hF.HumanEducatedYears = hf.HumanEducatedYears;
            hF.HumanEducatedMajor = hf.HumanEducatedMajor;
            hF.SalaryStandardId = hf.SalaryStandardId;
            hF.SalaryStandardName = hf.SalaryStandardName;
            hF.HumanBank = hf.HumanBank;
            hF.HumanAccount = hf.HumanAccount;
            hF.Checker = hf.Checker;
            hF.CheckTime = hf.CheckTime;
            hF.HumanSpeciality = hf.HumanSpeciality;
            hF.HumanHobby = hf.HumanHobby;
            hF.HumanHistroyRecords = hf.HumanHistroyRecords;
            hF.HumanFamilyMembership = hf.HumanFamilyMembership;
            hF.Remark = hf.Remark;
            hF.HumanPicture = hf.HumanPicture;
            hF.HumanFileStatus = hf.HumanFileStatus;
            hF.CheckStatus = hf.CheckStatus;
            hF.FileChangAmount = hf.FileChangAmount;
            hF.SalarySum = ss.SalarySum;
			myDbContext.HF.Update(hF);
            return await myDbContext.SaveChangesAsync() > 0;
        }

        public HFFenYE FenYeHFTJAsync(string firstKindName, string secondKindName, string thirdKindName, DateTime startDate, DateTime endDate, int page, int pageSize, int zt)
        {
            var query = myDbContext.HF.ToList();

            if (!string.IsNullOrEmpty(firstKindName))
            {
                query = query.Where(s => s.FirstKindName == firstKindName).ToList();
            }
            if (!string.IsNullOrEmpty(secondKindName))
            {
                query = query.Where(s => s.SecondKindName == secondKindName).ToList();
            }
            if (!string.IsNullOrEmpty(thirdKindName))
            {
                query = query.Where(s => s.ThirdKindName == thirdKindName).ToList();
            }
            if (startDate != default && endDate != default)
            {
                query = query.Where(s => s.RegistTime >= startDate && s.RegistTime <= endDate).ToList();
            }
            if (zt != 0)
            {
                query = query.Where(s => s.CheckStatus == zt).ToList();
            }

            int totalRecords = query.Count();
            var HF = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
            return new HFFenYE
            {
                totalRecords = totalRecords,
                hf = HF
            };
        }
        public HFFenYE FenYeHFGJZAsync(int page, int pageSize, int zt, string gjz)
        {
            var query = myDbContext.HF.ToList();

            if (!string.IsNullOrEmpty(gjz))
            {
                query = query.Where(s => s.HumanName.Contains(gjz)).ToList();
            }
            if (zt != 0)
            {
                query = query.Where(s => s.CheckStatus == zt).ToList();
            }

            int totalRecords = query.Count();
            var HF = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
            return new HFFenYE
            {
                totalRecords = totalRecords,
                hf = HF
            };
        }
        public async Task<bool> RemoveHFQAsyncHFS(string humanId,double DemandSalaraySum, double PaidSalarySum)
        {
            var hfToModify = await myDbContext.HF.FirstOrDefaultAsync(hf => hf.HumanId == humanId);
            if (hfToModify != null)
            {
                hfToModify.DemandSalaraySum = DemandSalaraySum;
                hfToModify.PaidSalarySum = PaidSalarySum;
                myDbContext.Attach(hfToModify);
                myDbContext.Entry(hfToModify).State = EntityState.Modified;
                await myDbContext.SaveChangesAsync();
                return true;
            }
            return false;
        }

        //根据档案编号查询出来对应的薪酬发放编号
        public async Task<string> GetSalaryGrantIdAsync(string HumanId)
        {
         var salaryGrant = await myDbContext.HF
         .Where(hf => hf.ThirdKindName == null && hf.HumanId == HumanId)
         .Select(hf => hf.SalaryStandardId) // 确保有这个属性  
         .FirstOrDefaultAsync(); // 第一个匹配项或 null  

            return salaryGrant; // 返回查询到的薪酬发放编号  
        }

		public HFFenYE HFFenYEZTAsync(string firstKindName, string secondKindName, string thirdKindName, string majorKindName, string majorName, DateTime startDate, DateTime endDate, int page, int pageSize, int zt1, int zt2)
		{
			var query = myDbContext.HF.ToList();

			if (!string.IsNullOrEmpty(firstKindName))
			{
				query = query.Where(s => s.FirstKindName == firstKindName).ToList();
			}
			if (!string.IsNullOrEmpty(secondKindName))
			{
				query = query.Where(s => s.SecondKindName == secondKindName).ToList();
			}
			if (!string.IsNullOrEmpty(thirdKindName))
			{
				query = query.Where(s => s.ThirdKindName == thirdKindName).ToList();
			}
			if (!string.IsNullOrEmpty(majorKindName))
			{
				query = query.Where(s => s.HumanMajorKindName == majorKindName).ToList();
			}
			if (!string.IsNullOrEmpty(majorName))
			{
				query = query.Where(s => s.HunmaMajorName == majorName).ToList();
			}
			if (startDate != default && endDate != default)
			{
				query = query.Where(s => s.RegistTime >= startDate && s.RegistTime <= endDate).ToList();
			}
			if (zt1 != 0)
			{
				query = query.Where(s => s.CheckStatus == zt1).ToList();
			}
			if (zt2 != 0)
			{
				query = query.Where(s => s.HumanFileStatus == zt2).ToList();
			}
			int totalRecords = query.Count();
			var HF = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
			return new HFFenYE
			{
				totalRecords = totalRecords,
				hf = HF
			};
		}

		public HFFenYE FenYeHFGJZZTAsync(int page, int pageSize, int zt1, int zt2, string gjz)
		{
			var query = myDbContext.HF.ToList();

			if (!string.IsNullOrEmpty(gjz))
			{
				query = query.Where(s => s.HumanName.Contains(gjz)).ToList();
			}
			if (zt1 != 0)
			{
				query = query.Where(s => s.CheckStatus == zt1).ToList();
			}
			if (zt2 != 0)
			{
				query = query.Where(s => s.HumanFileStatus == zt2).ToList();
			}

			int totalRecords = query.Count();
			var HF = query.Skip((page - 1) * pageSize).Take(pageSize).ToList();
			return new HFFenYE
			{
				totalRecords = totalRecords,
				hf = HF
			};
		}

		public async Task<bool> UpdateHFZTAsync(HF hf)
		{
			HF hF = myDbContext.HF.Where(e => e.HufId == hf.HufId).FirstOrDefault();
            hF.HumanFileStatus = hf.HumanFileStatus;
            hF.RecoveryTime = hf.RecoveryTime;
            hF.DeleteTime = hf.DeleteTime;
			myDbContext.HF.Update(hF);
			return await myDbContext.SaveChangesAsync() > 0;
		}

		public async Task<bool> DeleteHFAsync(int id)
		{
			HF hf = new HF()
			{
				HufId = id
			};
			myDbContext.HF.Remove(hf);
			int result = await myDbContext.SaveChangesAsync();
			return result>0;
		}

		public async Task<bool> UpdateHFMC(HF hF)
		{
            HF hF1 = myDbContext.HF.Where(e => e.HumanId == hF.HumanId).FirstOrDefault();
            if (hF1!=null)
            {
                hF1.HumanId = hF.HumanId;
				hF1.FirstKindId = hF.FirstKindId;
				hF1.FirstKindName = hF.FirstKindName;
				hF1.SecondKindId = hF.SecondKindId;
				hF1.SecondKindName = hF.SecondKindName;
				hF1.ThirdKindId = hF.ThirdKindId;
				hF1.ThirdKindName = hF.ThirdKindName;
				hF1.HumanMajorKindId = hF.HumanMajorKindId;
				hF1.HumanMajorKindName = hF.HumanMajorKindName;
				hF1.HumanMajorId = hF.HumanMajorId;
				hF1.HunmaMajorName = hF.HunmaMajorName;
				hF1.SalaryStandardId = hF.SalaryStandardId;
				hF1.SalaryStandardName = hF.SalaryStandardName;
				hF1.SalarySum = hF.SalarySum;
                hF1.HumanFileStatus = 1;
				myDbContext.HF.Update(hF1);
            }
			return await myDbContext.SaveChangesAsync() > 0;
		}

         
        public async Task<bool> UpdateHumanFileStatus(string humanId, int zt)
        {
            var humanFile = await myDbContext.HF.FirstOrDefaultAsync(hf => hf.HumanId == humanId);

            if (humanFile != null)
            {
                humanFile.HumanFileStatus = zt;

                await myDbContext.SaveChangesAsync();
                return true;
            }

            return false;
        }
    }
}
